package com.jams.goodox.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.login.LoginActivity;
import com.jams.goodox.activity.login.RoleChooseActivity;
import com.jams.goodox.activity.mine.question.MineQuestionBean;
import com.jams.goodox.activity.qa.ClassLearningActivity;
import com.jams.goodox.activity.qa.entity.Question;
import com.jams.goodox.activity.qa.teacher.QuestionAnswerDetailActivity;
import com.jams.goodox.activity.qa.teacher.TeacherAnswerActivity;
import com.jams.goodox.adapter.lfadapter.CommonRecycleViewAdapter;
import com.jams.goodox.adapter.lfadapter.HomeFragmentAdapter;
import com.jams.goodox.adapter.lfadapter.LFRecyclerViewHolder;
import com.jams.goodox.adapter.lfadapter.QaFragmentAdapter;
import com.jams.goodox.entity.PageInfo;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.net.services.MineService;
import com.jams.goodox.utils.ToastUtil;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 问答页面
 * @author HP
 */

public class QAFragment extends BaseFragment {

    private static final String TAG = "QAFragment";

    View rootView;

    @Bind(R.id.unlogin_show)
    LinearLayout unlogin_show;

    @Bind(R.id.recycleView)
    RecyclerView recycleView;


    private List<Question> questionBeanList =new ArrayList<>();
    private List<Question> unQABeanList =new ArrayList<>();
    private List<Question> qaBeanList =new ArrayList<>();

    private QaFragmentAdapter pAdapter;

    private boolean hasOne = false;
    private boolean hasTwo = false;

    private Intent intent;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.qa_fragment, container, false);
            // 初始化页面
            ButterKnife.bind(this, rootView);
        }
        ButterKnife.bind(this, rootView);

        init();
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getData();
    }

    private void init() {
        pAdapter = new QaFragmentAdapter(getActivity(),questionBeanList);
        recycleView.setLayoutManager(new LinearLayoutManager(getContext()));

        recycleView.setAdapter(pAdapter);

        pAdapter.setOnItemClickListener(new QaFragmentAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick( int position,boolean isAnswer) {
                Log.d(TAG," == " + questionBeanList.get(position).toString());
                if(!isAnswer){
                    intent = new Intent(getActivity(),TeacherAnswerActivity.class);
                    intent.putExtra("questionId",questionBeanList.get(position).getId());
                }else {
                    intent = new Intent(getActivity(),QuestionAnswerDetailActivity.class);
                    intent.putExtra("questionId",questionBeanList.get(position).getId());
                }
                startActivity(intent);
            }
        });
    }

    //我的问答接口
    private void getData(){
        clearMap();
        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).teacherQA(ProtocolManagers.getRequestMap("{" + "memberId:" + SePref.getId() + "}"));
        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        Log.d(TAG,"responseData == " + jsonObject.getString("responseData"));
                        JSONArray jsonArray = new JSONArray(jsonObject.getString("responseData"));
                        unQABeanList.clear();
                        qaBeanList.clear();
                        for (int i = 0; i < jsonArray.length(); i ++){
                            JSONObject object = jsonArray.getJSONObject(i);
                            Question question = new Question();
                            //问答状态(0未回答，1已回答，2已查看答案)
                            question.setId(object.getInt("id"));
                            question.setCreateTime(object.getLong("createTime"));
                            question.setNickName(object.getString("nickName"));
                            question.setTitle(object.getString("title"));
                            question.setImgPath(object.getString("imgPath"));
                            question.setType(1);

                            if(0 == object.getInt("queState")){
                                if(!hasOne){
                                    unQABeanList.add(new Question(0,false));
                                    //questionBeanList.add(new Question(0,false));
                                    hasOne = true;
                                }
                                question.setAnswer(false);
                                unQABeanList.add(question);
                            } else /*if(2 == object.getInt("queState"))*/{
                                if(!hasTwo){
                                    qaBeanList.add(new Question(0,true));
                                    //questionBeanList.add(new Question(0,true));
                                    hasTwo = true;
                                }
                                question.setAnswer(true);
                                qaBeanList.add(question);
                            }

                            //questionBeanList.add(question);

                            Log.d(TAG, "question = " + question.toString());
                        }

                        questionBeanList.addAll(unQABeanList);
                        questionBeanList.addAll(qaBeanList);
                        pAdapter.notifyDataSetChanged();

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG,"onResume = " );
        if (!SePref.isLogin()){
            unlogin_show.setVisibility(View.VISIBLE);
            recycleView.setVisibility(View.GONE);
        }else {
            unlogin_show.setVisibility(View.GONE);
            recycleView.setVisibility(View.VISIBLE);
            questionBeanList.clear();
            hasOne = false;
            hasTwo = false;
            getData();
        }
    }
}
